/**
 * @Project:
 * @Author: wanghong
 * @Date: 2019年03月11日
 * @Copyright: ©2019-2028 www.xfxb.net Inc. All rights reserved.
 */
package com.carryking.http.proxy.ssr;

import com.carryking.http.proxy.ssr.netty.ProxyChannelInboundHandle;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wanghong
 * @date 2019年03月11日
 */
public class Bootstrap {

    private final static Logger log = LoggerFactory.getLogger("Main");

    public static void main(String[] args) throws InterruptedException {

        Integer port = 2090;

        if (args != null && args.length > 1) {
            for (int n = 0; n < args.length; n++) {
                if (StringUtils.equalsIgnoreCase(args[n], "-p")) {
                    if (args.length < n + 2) {
                        throw new RuntimeException("参数错误");
                    }
                    String ptr = args[n + 1];
                    try {
                        port = Integer.parseInt(ptr);
                    } catch (Exception e) {
                        throw new RuntimeException("端口号错误");
                    }
                }
            }
        }

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast("request", new HttpRequestDecoder())
                                    .addLast("response", new HttpResponseEncoder())
                                    .addLast("handle", new ProxyChannelInboundHandle());

                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            log.info("web proxy is start success !!!");
            log.info("bind on port:{}", port);

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

}
